package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.base.domain.Letter;
import cn.ibizlab.businesscentral.core.base.service.ILetterService;
import cn.ibizlab.businesscentral.core.base.filter.LetterSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"信件" })
@RestController("CentralApi-letter")
@RequestMapping("")
public class LetterResource {

    @Autowired
    public ILetterService letterService;

    @Autowired
    @Lazy
    public LetterMapping letterMapping;

    @PreAuthorize("hasPermission(this.letterMapping.toDomain(#letterdto),'iBizBusinessCentral-Letter-Create')")
    @ApiOperation(value = "新建信件", tags = {"信件" },  notes = "新建信件")
	@RequestMapping(method = RequestMethod.POST, value = "/letters")
    @Transactional
    public ResponseEntity<LetterDTO> create(@RequestBody LetterDTO letterdto) {
        Letter domain = letterMapping.toDomain(letterdto);
		letterService.create(domain);
        LetterDTO dto = letterMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.letterMapping.toDomain(#letterdtos),'iBizBusinessCentral-Letter-Create')")
    @ApiOperation(value = "批量新建信件", tags = {"信件" },  notes = "批量新建信件")
	@RequestMapping(method = RequestMethod.POST, value = "/letters/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<LetterDTO> letterdtos) {
        letterService.createBatch(letterMapping.toDomain(letterdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "letter" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.letterService.get(#letter_id),'iBizBusinessCentral-Letter-Update')")
    @ApiOperation(value = "更新信件", tags = {"信件" },  notes = "更新信件")
	@RequestMapping(method = RequestMethod.PUT, value = "/letters/{letter_id}")
    @Transactional
    public ResponseEntity<LetterDTO> update(@PathVariable("letter_id") String letter_id, @RequestBody LetterDTO letterdto) {
		Letter domain  = letterMapping.toDomain(letterdto);
        domain .setActivityid(letter_id);
		letterService.update(domain );
		LetterDTO dto = letterMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.letterService.getLetterByEntities(this.letterMapping.toDomain(#letterdtos)),'iBizBusinessCentral-Letter-Update')")
    @ApiOperation(value = "批量更新信件", tags = {"信件" },  notes = "批量更新信件")
	@RequestMapping(method = RequestMethod.PUT, value = "/letters/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<LetterDTO> letterdtos) {
        letterService.updateBatch(letterMapping.toDomain(letterdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.letterService.get(#letter_id),'iBizBusinessCentral-Letter-Remove')")
    @ApiOperation(value = "删除信件", tags = {"信件" },  notes = "删除信件")
	@RequestMapping(method = RequestMethod.DELETE, value = "/letters/{letter_id}")
    @Transactional
    public ResponseEntity<Boolean> remove(@PathVariable("letter_id") String letter_id) {
         return ResponseEntity.status(HttpStatus.OK).body(letterService.remove(letter_id));
    }

    @PreAuthorize("hasPermission(this.letterService.getLetterByIds(#ids),'iBizBusinessCentral-Letter-Remove')")
    @ApiOperation(value = "批量删除信件", tags = {"信件" },  notes = "批量删除信件")
	@RequestMapping(method = RequestMethod.DELETE, value = "/letters/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        letterService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.letterMapping.toDomain(returnObject.body),'iBizBusinessCentral-Letter-Get')")
    @ApiOperation(value = "获取信件", tags = {"信件" },  notes = "获取信件")
	@RequestMapping(method = RequestMethod.GET, value = "/letters/{letter_id}")
    public ResponseEntity<LetterDTO> get(@PathVariable("letter_id") String letter_id) {
        Letter domain = letterService.get(letter_id);
        LetterDTO dto = letterMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取信件草稿", tags = {"信件" },  notes = "获取信件草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/letters/getdraft")
    public ResponseEntity<LetterDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(letterMapping.toDto(letterService.getDraft(new Letter())));
    }

    @ApiOperation(value = "检查信件", tags = {"信件" },  notes = "检查信件")
	@RequestMapping(method = RequestMethod.POST, value = "/letters/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody LetterDTO letterdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(letterService.checkKey(letterMapping.toDomain(letterdto)));
    }

    @PreAuthorize("hasPermission(this.letterMapping.toDomain(#letterdto),'iBizBusinessCentral-Letter-Save')")
    @ApiOperation(value = "保存信件", tags = {"信件" },  notes = "保存信件")
	@RequestMapping(method = RequestMethod.POST, value = "/letters/save")
    public ResponseEntity<Boolean> save(@RequestBody LetterDTO letterdto) {
        return ResponseEntity.status(HttpStatus.OK).body(letterService.save(letterMapping.toDomain(letterdto)));
    }

    @PreAuthorize("hasPermission(this.letterMapping.toDomain(#letterdtos),'iBizBusinessCentral-Letter-Save')")
    @ApiOperation(value = "批量保存信件", tags = {"信件" },  notes = "批量保存信件")
	@RequestMapping(method = RequestMethod.POST, value = "/letters/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<LetterDTO> letterdtos) {
        letterService.saveBatch(letterMapping.toDomain(letterdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Letter-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Letter-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"信件" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/letters/fetchdefault")
	public ResponseEntity<List<LetterDTO>> fetchDefault(LetterSearchContext context) {
        Page<Letter> domains = letterService.searchDefault(context) ;
        List<LetterDTO> list = letterMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Letter-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Letter-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"信件" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/letters/searchdefault")
	public ResponseEntity<Page<LetterDTO>> searchDefault(@RequestBody LetterSearchContext context) {
        Page<Letter> domains = letterService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(letterMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

